﻿namespace VisualSVN.Core.Licensing
{
    using System;
    using System.Text;

    public class KeyStringFormatter
    {
        public static readonly string ClosingKeySymbols = new string('-', 50);
        public const int KeyLineWidth = 50;
        public static readonly string OpeningKeySymbols = new string('-', 50);
        public static readonly char[] ReplaceSymbols = new char[] { '\n', '\r', '\t', ' ', '-' };

        public static string FormatKey(string pureKey)
        {
            StringBuilder builder = new StringBuilder(pureKey.Length);
            builder.Append(OpeningKeySymbols);
            builder.Append("\r\n");
            int startIndex = 0;
            while ((startIndex + 50) <= pureKey.Length)
            {
                builder.Append(pureKey.Substring(startIndex, 50));
                builder.Append("\r\n");
                startIndex += 50;
            }
            builder.Append(pureKey.Substring(startIndex, pureKey.Length % 50));
            builder.Append("\r\n");
            builder.Append(ClosingKeySymbols);
            return builder.ToString();
        }

        public static string ParseKey(string formattedKey)
        {
            return RemoveChars(formattedKey, ReplaceSymbols);
        }

        private static string RemoveChars(string str, char[] charsToRemove)
        {
            StringBuilder builder = new StringBuilder(str);
            foreach (char ch in charsToRemove)
            {
                builder.Replace(ch.ToString(), "");
            }
            return builder.ToString();
        }
    }
}

